<template>
  <view class="container">
    <Loading :show="isLoading" />
    <view class="form-group">
      <view class="form-item">
        <text class="label">头像</text>
        <view class="avatar-upload" @click="chooseAvatar">
          <image
            class="avatar"
            :src="
              formData.avatar ||
              'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
            "
            mode="aspectFill"
          />
          <text class="upload-text">点击更换头像</text>
        </view>
      </view>

      <view class="form-item">
        <text class="label">名称</text>
        <input
          class="input"
          v-model="formData.username"
          placeholder="请输入名称"
        />
      </view>

      <view class="form-item">
        <text class="label">邮箱</text>
        <input
          class="input"
          v-model="formData.email"
          placeholder="请输入邮箱"
          @input="onEmailInput"
        />
      </view>

      <view v-if="showEmailVerify" class="form-item">
        <text class="label">邮箱验证码</text>
        <view style="display: flex; gap: 10px;">
          <input
            class="input"
            v-model="emailCode"
            placeholder="请输入验证码"
            style="flex: 1;"
          />
          <button
            :disabled="emailBtnDisabled || emailCountdown > 0"
            @click="getEmailCodeHandler"
            style="width: 120px;"
          >
            {{ emailCountdown > 0 ? emailCountdown + 's后重试' : '获取验证码' }}
          </button>
        </view>
      </view>

      <view class="form-item">
        <text class="label">电话</text>
        <input
          class="input"
          v-model="formData.phone"
          placeholder="请输入电话"
        />
      </view>

      <view class="form-item">
        <text class="label">性别</text>
        <view class="gender-group">
          <view
            class="gender-option"
            :class="{ active: formData.gender === '1' }"
            @click="formData.gender = '1'"
          >
            <text>男</text>
          </view>
          <view
            class="gender-option"
            :class="{ active: formData.gender === '2' }"
            @click="formData.gender = '2'"
          >
            <text>女</text>
          </view>
        </view>
      </view>
    </view>

    <view class="button-group">
      <button class="save-btn" @click="saveProfile">保存</button>
      <button class="cancel-btn" @click="goBack">取消</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, onUnmounted } from "vue";
import { getEmailCode, verifyEmailCode } from '@/api/email';
import { uploadAvatar } from '@/api/oss';
import { updateUserInfo } from '@/api/user';
import Loading from '@/components/Loading.vue';

const formData = reactive({
  id: 0,
  avatar: "",
  username: "",
  email: "",
  phone: "",
  gender: "",
  tempAvatarPath: "",
  ossId: "",
});

const originalEmail = ref("");
const showEmailVerify = ref(false);
const emailCode = ref("");
const emailBtnDisabled = ref(false);
const emailCountdown = ref(0);
let emailTimer: any = null;
const emailVerified = ref(false);
const isLoading = ref(false);

const onEmailInput = () => {
  showEmailVerify.value = formData.email && formData.email !== originalEmail.value;
  emailVerified.value = false;
};

const getEmailCodeHandler = async () => {
  if (!formData.email) {
    uni.showToast({ title: "请输入邮箱", icon: "none" });
    return;
  }
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!emailRegex.test(formData.email)) {
    uni.showToast({ title: "邮箱格式不正确", icon: "none" });
    return;
  }
  emailBtnDisabled.value = true;
  isLoading.value = true;
  try {
    const res = await getEmailCode(formData.email);
    console.log(res);
    uni.showToast({ title: "验证码已发送", icon: "success" });
    emailCountdown.value = 60;
    emailTimer = setInterval(() => {
      emailCountdown.value--;
      if (emailCountdown.value <= 0) {
        clearInterval(emailTimer);
        emailBtnDisabled.value = false;
      }
    }, 1000);
  } catch (e) {
    emailBtnDisabled.value = false;
  }
  isLoading.value = false;
};

const verifyEmailCodeHandler = async () => {
  if (!emailCode.value) {
    uni.showToast({ title: "请输入验证码", icon: "none" });
    return false;
  }
  isLoading.value = true;
  try {
    const res = await verifyEmailCode(formData.email, emailCode.value);
    if (res.data) {
      emailVerified.value = true;
      uni.showToast({ title: "验证成功", icon: "success" });
      isLoading.value = false;
      return true;
    } else {
      uni.showToast({ title: "验证码错误", icon: "error" });
      isLoading.value = false;
      return false;
    }
  } catch (e) {
    uni.showToast({ title: "验证失败", icon: "error" });
    isLoading.value = false;
    return false;
  }
};

// 选择头像
const chooseAvatar = () => {
  const token = uni.getStorageSync("token");
  if (!token) {
    uni.showToast({
      title: "请先登录",
      icon: "error",
    });
    return;
  }
  isLoading.value = true;
  uni.chooseImage({
    count: 1,
    sizeType: ["compressed"],
    sourceType: ["album", "camera"],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0];
      formData.tempAvatarPath = tempFilePath;
      formData.avatar = tempFilePath;
      isLoading.value = false;
    },
    fail: (error) => {
      console.error("选择图片失败：", error);
      uni.showToast({
        title: "选择图片失败",
        icon: "error",
      });
      isLoading.value = false;
    },
  });
};

// 保存资料
const saveProfile = async () => {
  if (!formData.gender) {
    formData.gender = "0";
  }
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (formData.email && !emailRegex.test(formData.email)) {
    uni.showToast({
      title: "邮箱格式不正确",
      icon: "error",
      duration: 2000,
    });
    return;
  }
  if (showEmailVerify.value && !emailVerified.value) {
    const ok = await verifyEmailCodeHandler();
    if (!ok) return;
  }
  isLoading.value = true;
  try {
    let avatarUrl = formData.avatar;
    let ossId = formData.ossId;
    if (formData.tempAvatarPath) {
      const uploadResult = await uploadAvatar(formData.tempAvatarPath);
      avatarUrl = uploadResult.data.url;
      ossId = uploadResult.data.ossId;
    }
    await updateUserInfo({
      id: formData.id,
      username: formData.username,
      email: formData.email,
      phone: formData.phone,
      gender: formData.gender,
      avatar: ossId,
    });
    const userInfo = uni.getStorageSync("userInfo") || {};
    Object.assign(userInfo, {
      ...formData,
      avatar: avatarUrl,
      ossId: ossId,
    });
    uni.setStorageSync("userInfo", userInfo);
    uni.showToast({
      title: "保存成功",
      icon: "success",
      duration: 2000,
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 2000);
  } catch (error) {
    console.error("保存失败：", error);
  }
  isLoading.value = false;
};

const goBack = () => {
  uni.navigateBack();
};

onMounted(() => {
  const userInfo = uni.getStorageSync("userInfo");
  if (userInfo) {
    formData.id = userInfo.id;
    formData.avatar = userInfo.avatar;
    formData.ossId = userInfo.ossId || "";
    formData.username = userInfo.username;
    formData.email = userInfo.email;
    formData.phone = userInfo.phone;
    formData.gender = userInfo.gender;
    originalEmail.value = userInfo.email;
  }
});
onUnmounted(() => {
  if (emailTimer) clearInterval(emailTimer);
});
</script>

<style>
.container {
  padding: 20px;
}

.form-group {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.form-item {
  margin-bottom: 20px;
}

.label {
  display: block;
  margin-bottom: 8px;
  font-size: 16px;
  color: #333;
}

.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 2px solid #f0f0f0;
}

.upload-text {
  font-size: 14px;
  color: #666;
}

.input {
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 0 12px;
  font-size: 16px;
}

.button-group {
  display: flex;
  gap: 15px;
}

.save-btn,
.cancel-btn {
  flex: 1;
  height: 44px;
  border-radius: 22px;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.save-btn {
  background-color: #007aff;
  color: white;
}

.cancel-btn {
  background-color: #f0f0f0;
  color: #333;
}

.gender-group {
  display: flex;
  gap: 20px;
}

.gender-option {
  flex: 1;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #333;
  cursor: pointer;
  transition: all 0.3s ease;
}

.gender-option.active {
  background-color: #007aff;
  color: white;
  border-color: #007aff;
}
</style>
